import { RbacMenuType } from '@/datatypes/rbacMenu/data';
import {handleAdd, handleRemove, handleRemoveList, handleUpdate, list, page} from '@/services';

import {
  ActionType,
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';

import { IsValueEnum } from '@/enums/auth';
import { IconOutlinedValueEnum } from '@/enums/icon';
import AddPermForm from '@/pages/auth/rbacMenu/components/AddPermForm';
import UpdateForm from '@/pages/auth/rbacMenu/components/UpdateForm';
import { rbacMenuUrl, rbacPermissionMenuBtnUrl } from '@/urls';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Drawer } from 'antd';
import React, { useRef, useState } from 'react';

const TableList: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<RbacMenuType>();
  const [selectedRowsState, setSelectedRows] = useState<RbacMenuType[]>([]);

  const [addPermModalVisible, handleAddPermModalVisible] = useState<boolean>(false);

  // @ts-ignore
  const columns: ProColumns<RbacMenuType>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '名称',
      dataIndex: 'cnName',
    },
    {
      title: '菜单名称',
      dataIndex: 'name',
    },

    {
      title: '图标',
      dataIndex: 'icon',
      hideInSearch: true,
      render: (text) => {
        if (typeof text === 'string' && IconOutlinedValueEnum[text]) {
          return IconOutlinedValueEnum[text];
        }
        return null;
      },
    },
    {
      title: '路由路径',
      dataIndex: 'path',
    },

    {
      title: '组件路径',
      dataIndex: 'component',
    },
    {
      title: '重定向路径',
      dataIndex: 'redirect',
      hideInSearch: true,
    },
    {
      title: '是否精确匹配',
      dataIndex: 'exact',
      valueEnum: IsValueEnum,
      hideInSearch: true,
    },

    {
      title: '父级id',
      dataIndex: 'parentId',
    },

    {
      title: '排序',
      dataIndex: 'sort',
      hideInSearch: true,
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
            setShowDetail(false);
          }}
        >
          更新
        </a>,
        <a
          key="auth"
          onClick={() => {
            handleAddPermModalVisible(true);
            setCurrentRow(record);
            setShowDetail(false);
          }}
        >
          授权
        </a>,
        <a
          key="remove"
          onClick={async () => {
            await handleRemove(rbacMenuUrl, record.id);
            if (actionRef.current) {
              await actionRef.current.reload();
            }
            setShowDetail(false);
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<RbacMenuType, API.PageParams>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params) => {
          // 递归树
          return list('auth/rbacMenu/recursiveMenus', params);
          //return page(rbacMenuUrl, params);
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemoveList(rbacMenuUrl, selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title="新建"
        width="400px"
        open={createModalVisible}
        onOpenChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(rbacMenuUrl, value as RbacMenuType);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '路由名称为必填项',
            },
          ]}
          width="md"
          name="component"
          label={'路由名称'}
          placeholder={'请输入路由名称'}
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '图标为必填项',
            },
          ]}
          width="md"
          name="icon"
          label="图标"
          placeholder="请选择图标"
          valueEnum={IconOutlinedValueEnum}
          fieldProps={{
            optionLabelProp: 'label',
          }}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '重定向路径为必填项',
            },
          ]}
          width="md"
          name="redirect"
          label={'重定向路径'}
          placeholder={'请输入重定向路径'}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '是否精确匹配 1：是，0否为必填项',
            },
          ]}
          width="md"
          name="exact"
          label={'是否精确匹配 1：是，0否'}
          placeholder={'请输入是否精确匹配 1：是，0否'}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '路由路径为必填项',
            },
          ]}
          width="md"
          name="path"
          label={'路由路径'}
          placeholder={'请输入路由路径'}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '菜单名称为必填项',
            },
          ]}
          width="md"
          name="name"
          label={'菜单名称'}
          placeholder={'请输入菜单名称'}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '父级id为必填项',
            },
          ]}
          width="md"
          name="parentId"
          label={'父级id'}
          placeholder={'请输入父级id'}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '菜单类型为必填项',
            },
          ]}
          width="md"
          name="menuType"
          label={'菜单类型'}
          placeholder={'请输入菜单类型'}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '排序为必填项',
            },
          ]}
          width="md"
          name="sort"
          label={'排序'}
          placeholder={'请输入排序'}
        />
      </ModalForm>
      <UpdateForm
        onSubmit={async (value: any) => {
          const success = await handleUpdate(rbacMenuUrl, value, currentRow);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />
      <AddPermForm
        onSubmit={async (value) => {
          const permissionIds = value?.targetKeys;
          const menuOrBtnId = currentRow?.id;
          const success = await handleAdd(rbacPermissionMenuBtnUrl, {
            permissionIds,
            menuOrBtnId,
            correlationType: 1,
          });

          if (success) {
            handleAddPermModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleAddPermModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={addPermModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<RbacMenuType>
            column={2}
            title={currentRow?.id}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<RbacMenuType>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
